/**
 * $Revision: 1.0 $
 * $Author: Geln Yang $
 * $Date: Sep 5, 2010 9:59:04 AM $
 *
 * Author: Geln Yang
 * Date  : Sep 5, 2010 9:59:04 AM
 *
 */
package com.gooex.service.schedual.impl;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.c4j.db.hibernate.HibernateUtil;
import org.c4j.freemarker.FreemarkerTools;
import org.c4j.mail.SpringMailSender;
import org.c4j.system.web.localize.Localizer;
import org.c4j.system.web.page.Page;
import org.hibernate.SessionFactory;

import com.gooex.domain.base.Category;
import com.gooex.domain.base.Order;
import com.gooex.domain.base.emun.OrderStatus;
import com.gooex.domain.common.Subscription;
import com.gooex.domain.common.SubscriptionUtil;
import com.gooex.service.base.ICategoryManager;
import com.gooex.service.base.IOrderManager;
import com.gooex.service.schedual.ISubscriptionManager;
import com.gooex.service.schedual.ISubscriptionService;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author Geln Yang
 * @version 1.0
 */
public class SubscriptionServiceImpl implements ISubscriptionService {
	private static final Log logger = LogFactory.getLog(SubscriptionServiceImpl.class);

	private SessionFactory sessionFactory;

	private IOrderManager orderManager;

	private ICategoryManager categoryManager;

	private ISubscriptionManager subscriptionManager;

	private SpringMailSender mailSender;

	private Localizer localizer = Localizer.defaultLocalizer();

	private String newOrderTemplatePath;

	private String headerTemplatePath;

	private String footerTemplatePath;

	private String titleTemplatePath;

	public void broadcast() {
		try {
			HibernateUtil.openSession(sessionFactory);
			String[] intervals = SubscriptionUtil.getTodayInterval();
			List<Category> topCategories = categoryManager.getMenuTopCategories();
			for (Category category : topCategories) {
				String categoryId = category.getId();

				OrderStatus[] statuses = new OrderStatus[] { OrderStatus.INVITING, OrderStatus.QUOTING };
				Page page = new Page(30, 1);
				List<Order> orders = orderManager.findOrdersByCategory(categoryId, statuses, page);
				if (orders == null || orders.size() == 0)
					continue;

				List<Subscription> subscriptions = subscriptionManager.getConfirmedSubscriptions(categoryId,
						intervals);
				if (subscriptions != null && subscriptions.size() > 0) {
					for (Subscription subscription : subscriptions) {

						String subject = generateSubject(categoryId);

						StringBuffer buffer = new StringBuffer();
						buffer.append(generateHedaerContent());
						buffer.append(generateSubscriptionContent(categoryId, orders));
						buffer.append(generateFooterContent());

						mailSender.sendMail(new String[] { subscription.getEmail() }, null, subject, buffer
								.toString());
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			HibernateUtil.closeSession(sessionFactory);
		}
	}

	public String generateSubject(String categoryId) throws IOException, TemplateException {
		Category category = categoryManager.getCategory(categoryId);

		Map<String, Object> root = new HashMap<String, Object>();
		root.put("category", category);
		root.put("localizer", localizer);

		Writer outWriter = new StringWriter();
		Template template = FreemarkerTools.loadTemplate(titleTemplatePath);
		template.process(root, outWriter);
		return outWriter.toString();
	}

	public String generateSubscriptionContent(String categoryId, List<Order> orders) throws IOException,
			TemplateException {
		Category category = categoryManager.getCategory(categoryId);

		Map<String, Object> root = new HashMap<String, Object>();
		root.put("category", category);
		root.put("orders", orders);
		root.put("localizer", localizer);

		Writer outWriter = new StringWriter();
		Template template = FreemarkerTools.loadTemplate(newOrderTemplatePath);
		template.process(root, outWriter);
		return outWriter.toString();
	}

	public String generateFooterContent() throws IOException, TemplateException {
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("localizer", localizer);

		Writer outWriter = new StringWriter();
		Template template = FreemarkerTools.loadTemplate(footerTemplatePath);
		template.process(root, outWriter);
		return outWriter.toString();
	}

	public String generateHedaerContent() throws IOException, TemplateException {
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("localizer", localizer);
		Writer outWriter = new StringWriter();
		Template template = FreemarkerTools.loadTemplate(headerTemplatePath);
		template.process(root, outWriter);
		return outWriter.toString();
	}

	public void setOrderManager(IOrderManager orderManager) {
		this.orderManager = orderManager;
	}

	public void setCategoryManager(ICategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}

	public void setSubscriptionManager(ISubscriptionManager subscriptionManager) {
		this.subscriptionManager = subscriptionManager;
	}

	public void setMailSender(SpringMailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setNewOrderTemplatePath(String newOrderTemplatePath) {
		this.newOrderTemplatePath = newOrderTemplatePath;
	}

	public void setHeaderTemplatePath(String headerTemplatePath) {
		this.headerTemplatePath = headerTemplatePath;
	}

	public void setFooterTemplatePath(String footerTemplatePath) {
		this.footerTemplatePath = footerTemplatePath;
	}

	public void setTitleTemplatePath(String titleTemplatePath) {
		this.titleTemplatePath = titleTemplatePath;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
